package com.example.wanghui

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import java.io.File
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream

class MainActivity : AppCompatActivity() {

    private lateinit var minNumber: EditText
    private lateinit var maxNumber: EditText
    private lateinit var calculateButton: Button
    private lateinit var stopButton: Button
    private lateinit var resultTextView: TextView

    private var job: Job? = null
    private val primes = mutableListOf<Int>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        title = "王僡 2022110546"

        minNumber = findViewById(R.id.minNumber)
        maxNumber = findViewById(R.id.maxNumber)
        calculateButton = findViewById(R.id.calculateButton)
        stopButton = findViewById(R.id.stopButton)
        resultTextView = findViewById(R.id.resultTextView)

        calculateButton.setOnClickListener {
            startPrimeCalculation()
        }

        stopButton.setOnClickListener {
            stopCalculation()
        }

        loadPrimes()
    }

    private fun startPrimeCalculation() {
        job?.cancel()
        resultTextView.text = ""
        val min = minNumber.text.toString().toIntOrNull() ?: return
        val max = maxNumber.text.toString().toIntOrNull() ?: return

        job = lifecycleScope.launch(Dispatchers.Default) {
            for (number in min..max) {
                if (isPrime(number)) {
                    withContext(Dispatchers.Main) {
                        primes.add(number)
                        updateUI(number)
                    }
                }

                delay(10)

                if (!isActive) {
                    break
                }
            }
            savePrimes()
        }
    }

    private fun stopCalculation() {
        job?.cancel()
        resultTextView.append("计算已停止\n")
    }

    private fun isPrime(num: Int): Boolean {
        if (num <= 1) return false
        for (i in 2 until Math.sqrt(num.toDouble()).toInt() + 1) {
            if (num % i == 0) return false
        }
        return true
    }

    private fun updateUI(prime: Int) {
        resultTextView.append("$prime\n")
    }

    private fun savePrimes() {
        val fileOutput = File(filesDir, "primes.txt")
        ObjectOutputStream(FileOutputStream(fileOutput)).use { it.writeObject(primes) }
    }

    private fun loadPrimes() {
        val fileInput = File(filesDir, "primes.txt")
        if (fileInput.exists()) {
            ObjectInputStream(fileInput.inputStream()).use {
                val loadedPrimes = it.readObject() as List<Int>
                primes.addAll(loadedPrimes)
                for (prime in primes) {
                    updateUI(prime)
                }
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_history -> {
                startActivity(Intent(this, HistoryActivity::class.java))
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}